package com.effective.java.equals;

import java.awt.Color;

public class CompositionAdheringContract {

	public static void main(String[] args) {

		ColorPoint p1 = new ColorPoint(1, 0, Color.BLUE);
		Point p2 = new Point(1, 0);
		ColorPoint p3 = new ColorPoint(1, 0, Color.RED);

		System.out.println("p1.equals(p2) = " + p1.equals(p2));
		System.out.println("p2.equals(p3) = " + p2.equals(p3));
		System.out.println("p1.equals(p3) = " + p1.equals(p3));
	}

	private static class Point {

		private final int x;
		private final int y;

		public Point(int x, int y) {

			this.x = x;
			this.y = y;
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public boolean equals(Object object) {

			if (!(object instanceof Point)) {
				return false;
			}

			Point p = (Point) object;
			return (p.x == this.x && p.y == this.y);
		}
	}

	private static class ColorPoint {

		private final Point point;
		private final Color color;

		public ColorPoint(int x, int y, Color color) {

			this.point = new Point(x, y);
			this.color = color;
		}

		@SuppressWarnings("unused")
		public Point asPoint() {

			return this.point;
		}

		@Override
		public boolean equals(Object object) {

			if (!(object instanceof ColorPoint)) {
				return false;
			}

			ColorPoint cp = (ColorPoint) object;
			return cp.point.equals(this.point) && cp.color.equals(this.color);
		}
	}
}
